package com.greenantmall.wxapi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.greenantmall.R;
import com.greenantmall.bean.Order;
import com.greenantmall.utils.PayCompleteListener;
import com.greenantmall.utils.iLog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.sourceforge.simcpux.Constants;
import net.sourceforge.simcpux.WeChatPayUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class PayActivity extends Activity implements IWXAPIEventHandler {

	private static IWXAPI api;
	private final static String TAG = "PayActivity";
	private static Context mContext;
	static List<AVObject> mCreatedOrdersList;;
	static PayCompleteListener mPayCompletListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;

		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

		api.registerApp(Constants.APP_ID);

//		api.handleIntent(getIntent(), this);
		mCreatedOrdersList = WeChatPayUtil.getInstance().mCreatedOrdersList;
		mPayCompletListener = WeChatPayUtil.getInstance().mPayCompletListener;
		wechatPay();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	public void onReq(BaseReq arg0) {
		// TODO Auto-generated method stub
		iLog.d(TAG, "onReq, errCode = " + arg0);
	}

	@Override
	public void onResp(BaseResp resp) {
		iLog.d(TAG, "onPayFinish, errCode = " + resp.errCode);
		/**
		 * 0 成功 展示成功页面 -1 错误
		 * 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。 -2 用户取消
		 * 无需处理。发生场景：用户不支付了，点击取消，返回APP。
		 */
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			if (resp.errCode == 0) {
				wechatPay();
				if (mCreatedOrdersList == null || mCreatedOrdersList.size() == 0) {
					// success
					if (mPayCompletListener != null) {
						mPayCompletListener.payComplete();
					}
				}

			} else if (resp.errCode == -1) {
				// fail
				finish();
			} else if (resp.errCode == -2) {
				// cancel

				finish();

			}

			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle(R.string.app_tip);
			builder.setMessage(mContext.getString(R.string.pay_result_callback_msg, String.valueOf(resp.errCode)));
			builder.show();
		}
	}

	private static void toWeChatpay(String content) {
		JSONObject json = null;
		try {
			json = new JSONObject(content);
			if (null != json && json.has("resultCode") && json.has("prepay_id")) {
				PayReq req = new PayReq();
				req.appId = Constants.APP_ID;
				// req.appId = json.getString("appid");
				/**
				 * **{"sign":"D77810F7970795985D80533323242B07",
				 * "timestamp":"1460989862", "noncestr":"pbEfxbspW3IHOSh6",
				 * "partnerid":"1293416501",
				 * "prepay_id":"wx201604182231260f347d701f0488470854",
				 * "resultCode":"SUCCESS", "package":"Sign=WXPay",
				 * "appid":"wx35393f4b8dc2cff0"}
				 */
				req.partnerId = json.getString("partnerid");
				req.prepayId = json.getString("prepay_id");
				req.nonceStr = json.getString("noncestr");
				req.timeStamp = json.getString("timestamp");
				req.packageValue = json.getString("package");
				req.sign = json.getString("sign");
//				req.extData = "app data"; // optional
				Toast.makeText(mContext, "正常调起支付", Toast.LENGTH_SHORT).show();
				api.sendReq(req);
			} else {
				iLog.d(TAG, "PAY_GET1:" + json.getString("resultCode"));
				Toast.makeText(mContext, " 返回错误 :" + content, Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			if (json != null)
				try {
					Toast.makeText(mContext, " 返回错误 " + json.getString("resultCode"), Toast.LENGTH_SHORT).show();
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
		}
	}

    public static void wechatPay() {
        if (api != null && mContext != null) {
            boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if (isPaySupported) {

                AVObject orderItem = null;
                if (mCreatedOrdersList != null && mCreatedOrdersList.size() > 0) {
                    Toast.makeText(mContext, "获取订单中...", Toast.LENGTH_SHORT).show();
                    orderItem = mCreatedOrdersList.remove(0);
                    final String orderId = orderItem.getString(Order.ATTR_ORDERID);
                    final double totalCost = orderItem.getDouble(Order.ATTR_TOTALCOST);

                    String userId = AVUser.getCurrentUser().getObjectId();
                    String url = "http://greenantmall.net/sgz/weixinorder.action?";
                    HttpUtils httpUtils = new HttpUtils();

                    RequestParams params = new RequestParams();
                    params.addBodyParameter("trans_id", orderId);
                    params.addBodyParameter("user_id", userId);
                    params.addBodyParameter("money", String.valueOf(totalCost));
                    httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {
                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            iLog.d(TAG, "CEXX => getDataFromNet => arg0 : " + arg0 + " orderId："
                                    + orderId + " totalCost："
                                    + totalCost + " msg:" + arg0.getMessage() + " "
                                    + arg0.getExceptionCode());
                            iLog.d(TAG, "CEXX => getDataFromNet => arg1 : " + arg1 + " orderId："
                                    + orderId + " totalCost:"
                                    + totalCost);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            String result = arg0.result;
                            iLog.d(TAG, "CEXX => getDataFromNet => result : " + result);
                            toWeChatpay(result);
                        }
                    });
                } else {
                    if (mCreatedOrdersList == null || mCreatedOrdersList.size() == 0) {
                        // success
                        if (mPayCompletListener != null) {
                            mPayCompletListener.payComplete();
                        }
                    }

                    ((Activity) mContext).finish();
                }

            } else {
                Toast.makeText(mContext, "请检查是否安装微信客户端", Toast.LENGTH_SHORT).show();
            }
        }

    }

    public static void checkErrorResult() {
        if (mCreatedOrdersList == null || mCreatedOrdersList.size() == 0) {

            if (mContext != null) {
                ((Activity) mContext).finish();
            }

        }

    }
}
